<template>
  <div class="page">
    <h2>随访与疗效评估</h2>
    <div class="controls">
      <el-input v-model="q" placeholder="按患者或随访内容搜索" clearable style="flex:1" @clear="onClear" />
      <el-select v-model="filterStatus" placeholder="随访状态" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="未随访" value="未随访" />
        <el-option label="进行中" value="进行中" />
        <el-option label="已完成" value="已完成" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增随访</el-button>
        <el-button @click="() => fileInput.click()">导入CSV</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <div class="muted">说明：记录随访时间表、疗效量表（PSQI/ISI/ESS）、症状变化、依从性与不良反应，支持随访提醒与计划管理。</div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="patient" label="患者" width="160" />
      <el-table-column prop="mrn" label="住院号" width="120" />
      <el-table-column prop="followDate" label="随访日期" width="140" />
      <el-table-column prop="scale" label="量表/评分" width="160" />
      <el-table-column prop="effect" label="疗效评价" width="140" />
      <el-table-column prop="adherence" label="依从性" width="120" />
      <el-table-column prop="adverse" label="不良反应" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">查看/编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑随访' : '新增随访'" v-model="showModal" width="820px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="患者姓名">
          <el-input v-model="form.patient" />
        </el-form-item>
        <el-form-item label="住院号/门诊号">
          <el-input v-model="form.mrn" />
        </el-form-item>
        <el-form-item label="随访日期">
          <el-date-picker v-model="form.followDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="量表/评分">
          <el-input v-model="form.scale" placeholder="例如：PSQI 8；ISI 16" />
        </el-form-item>
        <el-form-item label="疗效评价">
          <el-select v-model="form.effect" style="width:200px">
            <el-option label="无效" value="无效" />
            <el-option label="部分改善" value="部分改善" />
            <el-option label="显著改善" value="显著改善" />
          </el-select>
        </el-form-item>
        <el-form-item label="依从性">
          <el-select v-model="form.adherence" style="width:160px">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="不良反应/安全事件">
          <el-input type="textarea" v-model="form.adverse" />
        </el-form-item>
        <el-form-item label="调整建议/下一步">
          <el-input type="textarea" v-model="form.nextStep" />
        </el-form-item>
        <el-form-item label="随访状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="未随访" value="未随访" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".csv" style="display:none" @change="handleFile" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  {id:1,patient:'张三',mrn:'A1001',followDate:'2025-10-15',scale:'PSQI 8',effect:'部分改善',adherence:'中',adverse:'无',nextStep:'继续CBT-I',status:'已完成'},
  {id:2,patient:'李四',mrn:'A1002',followDate:'2025-10-10',scale:'ISI 14',effect:'显著改善',adherence:'高',adverse:'短暂嗜睡',nextStep:'减少药物剂量',status:'已完成'}
];

const data = ref([]);
const q = ref('');
const filterStatus = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ patient:'', mrn:'', followDate:'', scale:'', effect:'部分改善', adherence:'中', adverse:'', nextStep:'', status:'未随访' });
const fileInput = ref(null);

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }
function saveData(){ /* placeholder */ }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.patient.toLowerCase().includes(qq) || (d.mrn||'').toLowerCase().includes(qq) || (d.scale||'').toLowerCase().includes(qq))) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{patient:'',mrn:'',followDate:'',scale:'',effect:'部分改善',adherence:'中',adverse:'',nextStep:'',status:'未随访'}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.patient){ ElMessage.warning('请输入患者姓名'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); } saveData(); showModal.value=false; }

function deleteOne(id){ ElMessageBox.confirm('确认删除该随访记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); saveData(); ElMessage.success('已删除'); })
  .catch(()=>{});
}

function batchDelete(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); saveData(); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','patient','mrn','followDate','scale','effect','adherence','adverse','nextStep','status'], ...data.value.map(d=>[d.id,d.patient,d.mrn,d.followDate,d.scale,d.effect,d.adherence,d.adverse,d.nextStep,d.status]) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='followup_records.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function handleFile(e){ const f = e.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = function(ev){ try{ const text = ev.target.result; const rows = text.split(/\r?\n/).map(r=>r.trim()).filter(Boolean); if(rows.length<2){ ElMessage.warning('没有有效数据'); return; } const headers = parseCSVLine(rows[0]); const items = rows.slice(1).map(r=>parseCSVLine(r)).map(cols=>{ const obj={}; headers.forEach((h,i)=>obj[h.trim()]=cols[i]||''); return obj; }); items.forEach(it=>{ const id = it.id?parseInt(it.id):null; if(id){ const ex = data.value.find(x=>x.id===id); if(ex){ ex.patient = it.patient||ex.patient; ex.mrn = it.mrn||ex.mrn; ex.followDate = it.followDate||ex.followDate; ex.scale = it.scale||ex.scale; ex.effect = it.effect||ex.effect; ex.adherence = it.adherence||ex.adherence; ex.adverse = it.adverse||ex.adverse; ex.nextStep = it.nextStep||ex.nextStep; ex.status = it.status||ex.status; return; } } const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push({id:nid,patient:it.patient||'未命名',mrn:it.mrn||'',followDate:it.followDate||'',scale:it.scale||'',effect:it.effect||'部分改善',adherence:it.adherence||'中',adverse:it.adverse||'',nextStep:it.nextStep||'',status:it.status||'未随访'}); }); saveData(); ElMessage.success('导入完成'); }catch(err){ ElMessage.error('导入失败'); }}; reader.readAsText(f,'utf-8'); e.target.value=''; }

function parseCSVLine(line){ const cols=[]; let cur=''; let inQ=false; for(let i=0;i<line.length;i++){ const ch=line[i]; if(inQ){ if(ch==='"'){ if(line[i+1]==='"'){ cur+='"'; i++; }else{ inQ=false; } }else{ cur+=ch; } }else{ if(ch==='"'){ inQ=true; }else if(ch===','){ cols.push(cur); cur=''; }else{ cur+=ch; } } } cols.push(cur); return cols; }
function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>